package org.uu.mybatisplus.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class UuBeanUtils {

    public static <T> List<T> copyBeanList(List<?> sources, Class<T> cls) {

        if (CollectionUtils.isEmpty(sources)) {
            return Collections.emptyList();
        } else {
            List<T> results = new ArrayList<>(sources.size());
            try {
                for (Object source : sources) {
                    T t =  cls.getDeclaredConstructor().newInstance();
                    BeanUtils.copyProperties(source, t);
                    results.add(t);
                }
            } catch (InstantiationException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            }
            return results;
        }
    }
}
